<html>
    <script>
        // 仅仅用于控制哪一端的浏览器发起offer，#号后面有值的一方发起
        var isCaller = window.location.href.split('#')[1];

        // 与信令服务器的WebSocket连接
        //var socket = new WebSocket("wss://192.168.1.103:3000");
        var socket = new WebSocket("wss://deque.me:3000");

        // stun和turn服务器
        var iceServer = {
            "iceServers": [{
                "url": "stun:stun.l.google.com:19302"
            }, {
                "url": "turn:numb.viagenie.ca",
                "username": "webrtc@live.com",
                "credential": "muazkh"
            }]
        };

        //兼容浏览器的PeerConnection写法
        var PeerConnection = (window.PeerConnection ||
                            window.webkitPeerConnection00 || 
                            window.webkitRTCPeerConnection || 
                            window.mozRTCPeerConnection);
        //创建PeerConnection实例
        var pc = new PeerConnection(iceServer);

        // 发送ICE候选到其他客户端
        pc.onicecandidate = function(event){
            if (event.candidate !== null) {
                socket.send(JSON.stringify({
                    "event": "_ice_candidate",
                    "data": {
                        "candidate": event.candidate
                    }
                }));
            }
        };

        // 如果检测到媒体流连接到本地，将其绑定到一个video标签上输出
        pc.onaddstream = function(event){
            document.getElementById('remoteVideo').src = URL.createObjectURL(event.stream);
        };

        // 发送offer和answer的函数，发送本地session描述
        var sendOfferFn = function(desc){
            pc.setLocalDescription(desc);
            socket.send(JSON.stringify({ 
                "event": "_offer",
                "data": {
                    "sdp": desc
                }
            }));
        },
        sendAnswerFn = function(desc){
            pc.setLocalDescription(desc);
            socket.send(JSON.stringify({ 
                "event": "_answer",
                "data": {
                    "sdp": desc
                }
            }));
        };

        var getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);

        getUserMedia.call(navigator, {
            video: true,
            audio: true
        }, function(localMediaStream) {
            var video = document.getElementById('localVideo');
            video.src = window.URL.createObjectURL(localMediaStream);
            video.onloadedmetadata = function(e) {
                console.log("Label: " + localMediaStream.label);
                console.log("AudioTracks" , localMediaStream.getAudioTracks());
                console.log("VideoTracks" , localMediaStream.getVideoTracks());
            };
            //向PeerConnection中加入需要发送的流
            pc.addStream(localMediaStream);
            //如果是发起方则发送一个offer信令
            if(isCaller){
                pc.createOffer(sendOfferFn, function (error) {
                    console.log('Failure callback: ' + error);
                });
            }
        }, function(e) {
            console.log('Reeeejected!', e);
        });

        //处理到来的信令
        socket.onmessage = function(event){
            var json = JSON.parse(event.data);
            console.log('onmessage: ', json);
            //如果是一个ICE的候选，则将其加入到PeerConnection中，否则设定对方的session描述为传递过来的描述
            if( json.event === "_ice_candidate" ){
                pc.addIceCandidate(new RTCIceCandidate(json.data.candidate));
            } else {
                pc.setRemoteDescription(new RTCSessionDescription(json.data.sdp));
                // 如果是一个offer，那么需要回复一个answer
                if(json.event === "_offer") {
                    pc.createAnswer(sendAnswerFn, function (error) {
                        console.log('Failure callback: ' + error);
                    });
                }
            }
        };
    </script>

<body>
    Local: <br>
    <video id="localVideo" autoplay></video><br>
    Remote: <br>
    <video id="remoteVideo" autoplay></video>
</body>

</html>
